
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'StoreData.dart';


class Utils{
  ///使用md5加密
  static String generateMD5(String data) {
    Uint8List content = const Utf8Encoder().convert(data);
    Digest digest = md5.convert(content);
    return digest.toString();
  }
  ///判断是否为空
  static bool isEmpty<T>(dynamic val){
    if(val==null || val=="" || val.toString()==""){
      return true;
    }
    return false;
  }

  ///判断是否未JSON
  static bool isJson(dynamic value){
    if(value!=null && value.runtimeType.toString()=="String"){
      try{
        const JsonDecoder().convert(value);
        return true;
      }catch(e){
        return false;
      }
    }
    return false;

  }

  ///数据字典value转换为TEXT
  static dynamic filterDictText(String dictCode,Map replaceFields, dynamic val){

    if(dictCode.isEmpty || val.isEmpty){
      return val;
    }
    List dictOptions = StoreData.dictInfo[dictCode];
    if(dictOptions ==null || dictOptions.isEmpty){
      return val;
    }

    if(StoreData.dictVal2Text[dictCode] == null){
      StoreData.dictVal2Text[dictCode] = {};
    }
    if(StoreData.dictVal2Text[dictCode]![val]!=null){
      return StoreData.dictVal2Text[dictCode]![val];
    }

    var reArr = dictOptions.where((item){
      return item["itemValue"]==val || item["value"]==val || (replaceFields.isNotEmpty?item[replaceFields['itemValue']]==val:false);
    });
    reArr.toList();
    if(reArr.isNotEmpty){
      var text = val;
      if(reArr.first["itemText"]!=null){
        text = reArr.first["itemText"];
      }else if(reArr.first["title"]!=null){
        text = reArr.first["title"];
      }else if(replaceFields.isNotEmpty){
        text = reArr.first[replaceFields["itemText"]]??val;
      }
      StoreData.dictVal2Text[dictCode]![val] = text;
      return text;
    }else{
      var re = filterDictChildText(dictOptions,val);
      if(re!=null && re!=""){
        StoreData.dictVal2Text[dictCode]![val]=re;
      }
      return re;
    }
  }

  static dynamic filterDictChildText(dictOptions, val){
    var result="";
    for(var i=0;i<dictOptions.length;i++){
      if(dictOptions[i]["value"]==val){
        result = dictOptions[i]["title"];
        break;
      }else if(dictOptions[i]["children"]!=null){
        result = filterDictChildText(dictOptions[i]["children"],val);
      }
    }
    return result;
  }


  ///弹出Confirm
  static showConfirm(BuildContext context,String title,String content,{String? confirm,String? cancel})async{
    bool? isSelect = await showCupertinoDialog<bool>(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          content: Text(content),
          title: Text(title),
          actions: [
            CupertinoDialogAction(
              isDestructiveAction: true,
              onPressed: () {
                Navigator.of(context).pop(false);
              },
              child: Text(cancel??'取消'),
            ),
            CupertinoDialogAction(
              child: Text(confirm??'确认'),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );

    return isSelect;

  }

  ///获取包相关信息
  static getPackageInfo()async{
    // String appName = packageInfo.appName;
    // String packageName = packageInfo.packageName;
    // String version = packageInfo.version;
    // String buildNumber = packageInfo.buildNumber;
    return await PackageInfo.fromPlatform();
  }

  ///判断是否有按钮权限
  static bool isHaveBtn(String btnCode){
    List btns = StoreData.buttons;
    if(btns.isNotEmpty && btns.contains(btnCode)){
      return true;
    }
    return false;
  }

  ///判断网络图片
  static Future<bool> checkNetworkImageExists(String url) async {
    try {
      final response = await InternetAddress.lookup('example.com'); // 检查网络连接（仅为示例）
      if (response.isNotEmpty && response[0].rawAddress.isNotEmpty) {
        final httpClient = HttpClient();
        final request = await httpClient.getUrl(Uri.parse(url));
        final response = await request.close();
        if (response.statusCode == 200) {
          return true; // 图片存在且可访问
        } else {
          return false; // 无法访问，可能是404等错误状态码
        }
      } else {
        return false; // 没有网络连接
      }
    } catch (e) {
      return false; // 捕获异常，例如网络错误等
    }
  }

}